package controllers

import java.sql.Timestamp
import java.util.{Calendar, Date, Properties}
import javax.inject.Inject
import javax.mail._
import javax.mail.internet.{InternetAddress, MimeMessage}
import play.api.data.Form
import play.api.data.Forms._
import play.api.mvc._
import models.Tables._
import dao._
import org.joda.time.DateTime

import scala.concurrent.ExecutionContext.Implicits.global

/**
  * Created by yz on 2017/6/20.
  */
case class SubmissionData(name: String, email: String, subject: String, message: String)

class ContactController @Inject()(submissionDao: SubmissionDao,cc: ControllerComponents) extends AbstractController(cc) {

  val form = Form(
    mapping(
      "name" -> text,
      "email" -> text,
      "subject" -> text,
      "message" -> text
    )(SubmissionData.apply)(SubmissionData.unapply)
  )

  def toIndex = Action {
    Ok(views.html.contact.index())
  }

  def insertSubmission = Action.async { implicit request =>
    val data = form.bindFromRequest.get
    val submission = SubmissionRow(id = 0, time = new DateTime(new Date()), email = data.email, name = data.name,
      subject = data.subject,message = data.message)
    submissionDao.insert(submission).map { x =>
      Ok("success!")
    }
  }

  def sendMail = Action { implicit request =>
    val data = form.bindFromRequest.get
    val props = new Properties()
    props.put("mail.smtp.auth", "true")
    val mailSession = javax.mail.Session.getDefaultInstance(props, null)
    val transport = mailSession.getTransport("smtp")
    val message = new MimeMessage(mailSession)
    message.setSubject("Data submission")
    val nick = internet.MimeUtility.encodeText("exoRBase")
    message.setFrom(new InternetAddress(nick + "<exorbase@vgenomics.cn>"))
    message.addRecipient(Message.RecipientType.TO, new InternetAddress("slhuang@fudan.edu.cn"))
    val content = "Name:<br>" + data.name + "<br><br>Email address:<br>" + data.email + "<br><br>Subject:<br>" + data.subject + "<br><br>Message:<br>" + data.message
    message.setContent(content, "text/html;charset=utf-8")
    transport.connect("smtp.exmail.qq.com", "exorbase@vgenomics.cn", "exoR123")
    transport.sendMessage(message, message.getRecipients(Message.RecipientType.TO))
    transport.close()
    Ok("success")
  }
}
